package com.amkai.aes.webservice.mobile.objecthandler;

import java.util.ArrayList;
import java.util.List;

import com.amkai.aes.generatedbeans.organization.BusinessGroup;
import com.amkai.aes.generatedbeans.organization.Department;
import com.amkai.aes.webservice.mobile.MobileJobObjectHandler;
import com.amkai.common.extensions.hibernate.config.SiteManager;
import com.amkai.common.extensions.hibernate.config.manager.SessionManager;
import com.amkai.mobile.bean.organization.MobileBusinessEntity;
import com.amkai.mobile.bean.organization.MobileBusinessGroup;
import com.amkai.mobile.common.job.organization.MobileOrganizationJob;
import com.amkai.mobile.common.job.organization.MobileOrganizationJobResult;

public class MobileOrganizationJobHandler implements MobileJobObjectHandler<MobileOrganizationJob, MobileOrganizationJobResult> {

	@Override
	public MobileOrganizationJobResult process(MobileOrganizationJob job) throws Exception {
		// TODO Auto-generated method stub
		MobileOrganizationJobResult result = new MobileOrganizationJobResult();
		SessionManager sm = SiteManager.Start();
		List<Long> businessGroupIds =  sm.execute("SELECT bg.id FROM BusinessGroup bg WHERE bg.active = 1").list();
		sm.clear();
		for (Long bgId : businessGroupIds) {

			putBgToJobResult(sm, bgId, result);
			sm.clear();
		}
		return result;
	}

	private void putBgToJobResult(SessionManager sm, Long bgId, MobileOrganizationJobResult result) throws Exception {
		BusinessGroup bg = sm.get(BusinessGroup.class, bgId);
		if (result.businessGroups == null){
			result.businessGroups = new ArrayList<MobileBusinessGroup>();
		}
		MobileBusinessGroup mbg = new MobileBusinessGroup();
		mbg.businessEntities = new ArrayList<MobileBusinessEntity>();
		mbg.id= bg.getId();
		mbg.name = bg.getName();
		List<Long> businessEntityIds =  sm.execute("SELECT be.id FROM Department be  WHERE be.active = 1 and be.parent.id =  " +  bgId).list();
		for (Long beId : businessEntityIds) {
			Department be = sm.get(Department.class, beId);
			MobileBusinessEntity mbe = new MobileBusinessEntity();
			mbe.id = beId;
			mbe.name = be.getName();
			mbe.shortName = be.getShortName();
			mbg.businessEntities.add(mbe);
		}
		result.businessGroups.add(mbg);
	}

}
